<template>
  <!-- 地址列表页面 -->
  <view class="address-page">
    <!-- 新增地址按钮 -->
    <view class="add-btn" @click="handleAddAddress">
      <text>+ 新增收货地址</text>
    </view>

    <!-- 地址列表 -->
    <scroll-view class="address-list" scroll-y>
      <view class="address-item" v-for="(item, index) in addressList" :key="item.id" @click="handleEditAddress(item)">
        <!-- 地址信息 -->
        <view class="address-content">
          <view class="header">
            <text class="name">{{ item.consignee }}</text>
            <text class="phone">{{ item.phone_number }}</text>
            <text class="default" v-if="item.is_default">默认</text>
          </view>
          <view class="address">{{ removeXieRegion(item.province_city_district) + item.address_detail }}</view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-btns">
          <view class="btn edit-btn" @click.stop="handleEditAddress(item)">编辑</view>
          <view class="btn delete-btn" @click.stop="handleDeleteAddress(item.id)">删除</view>
        </view>
      </view>
    </scroll-view>

    <!-- 新增/编辑地址弹窗 -->
    <uni-popup ref="popup" type="bottom">
      <view class="address-form">
        <view class="form-title">{{ isEdit ? '编辑地址' : '新增地址' }}</view>
        <uni-forms ref="form" :modelValue="formData" :rules="rules">
          <!-- 表单字段 -->

          <uni-forms-item label="收货人" name="consignee" required>
            <uni-easyinput v-model="formData.consignee" placeholder="请输入姓名" />
          </uni-forms-item>

          <uni-forms-item label="联系电话" name="phone_number" required>
            <uni-easyinput v-model="formData.phone_number" type="number" placeholder="请输入手机号" />
          </uni-forms-item>

          <uni-forms-item label="所在地区" name="region" required>
            <uni-data-picker
              v-model="formData.region[formData.region.length - 1]"
              :localdata="cityData"
              popup-title="请选择地区"
              @change="onchangeRegion"
            ></uni-data-picker>
          </uni-forms-item>

          <uni-forms-item label="详细地址" name="address_detail" required>
            <uni-easyinput v-model="formData.address_detail" type="textarea" placeholder="街道门牌号等详细信息" />
          </uni-forms-item>

          <view class="default-switch">
            <text>设为默认地址</text>
            <switch :checked="formData.is_default" @change="onSwitchChange" />
          </view>

          <!-- 操作按钮 -->
          <view class="form-btns">
            <button class="cancel-btn" @click="closePopup">取消</button>
            <button class="confirm-btn" @click="submitForm">保存</button>
          </view>
        </uni-forms>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import allCity from '../../utils/cityLocalData'

export default {
  data() {
    return {
      cityData: [],
      isEdit: false,
      currentIndex: -1,
      user_id: '',
      formData: {
        consignee: '',

        phone_number: '',
        region: [],
        province_city_district: '',
        address_detail: '',
        is_default: false
      },
      addressList: [],
      rules: {
        consignee: {
          // name 字段的校验规则
          rules: [
            // 校验 name 不能为空
            {
              required: true,
              errorMessage: '请填写收件人'
            },
            // 对name字段进行长度验证
            {
              minLength: 1,
              maxLength: 5,
              errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符'
            }
          ],
          // 当前表单域的字段中文名，可不填写
          label: '收件人',
          validateTrigger: 'submit'
        },
        phone_number: {
          rules: [
            {
              required: true,
              errorMessage: '请输入联系电话'
            },
            {
              format: 'number',
              errorMessage: '请输入合法的手机号'
            },
            {
              pattern: '^(?:\\+?86)?1(?:3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[134578]|8[0-9]|9[0-35-9])\\d{8}$',
              errorMessage: '请输入合法的手机号'
            }
          ],
          // 当前表单域的字段中文名，可不填写
          label: '手机号',
          validateTrigger: 'submit'
        },
        region: {
          rules: [
            {
              required: true,
              errorMessage: '请输入地区'
            }
          ],

          label: '地区',
          validateTrigger: 'submit'
        },
        address_detail: {
          rules: [
            {
              required: true,
              errorMessage: '请输入详细地址'
            },
            {
              minLength: 3,
              maxLength: 200,
              errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符'
            }
          ],

          label: '详细地址',
          validateTrigger: 'submit'
        }
      }
    }
  },

  onLoad() {
    this.cityData = allCity
    // 获取id
    this.user_id = parseInt(getApp().globalData.userInfo.id)
    this.getData()
  },

  methods: {
    async getData() {
      // 模拟异步请求
      const { data: res } = await uni.request({
        url: this.$domain.data + '/getAllAddressByUid/' + this.user_id,
        header: getApp().globalData.header
      })

      if (res.status !== 200) {
        this.$checkStatus(res.status, '获取地址失败')
        return
      }

      this.addressList = res.data
    },

    onchangeRegion(e) {
      this.formData.region = e.detail.value
    },

    // 打开新增地址弹窗
    handleAddAddress() {
      this.isEdit = false
      this.resetForm()
      this.$refs.popup.open()
    },

    // 打开编辑地址弹窗
    handleEditAddress(item) {
      this.isEdit = true
      const region = item.province_city_district.split('/')
      this.formData = { ...item, region: [...region] }
      this.$refs.popup.open()
    },

    // 删除地址
    handleDeleteAddress(id) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: async (res) => {
          if (res.confirm) {
            const { data: res } = await uni.request({
              url: this.$domain.data + '/deleteAddress/' + id,
              method: 'POST',
              header: getApp().globalData.header
            })

            if (res.status !== 200) {
              this.$checkStatus(res.status, '删除失败')
              return
            }

            this.getData()
            uni.showToast({ title: '删除成功' })
          }
        }
      })
    },

    // 默认地址切换
    onSwitchChange(e) {
      this.formData.is_default = e.detail.value
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(async (res) => {
        if (res != null) {
          return
        }
        const newAddress = {
          ...this.formData
        }

        // console.log('添加')
        const region = newAddress.region
        if (region.length === 0) {
          uni.showToast('region未知错误，保存失败')
          return
        }

        // 测试 uid = 1
        newAddress.user_id = this.user_id

        // 拼接region
        newAddress.province_city_district = this.joinRegion(region)
        var res
        if (this.isEdit) {
          // console.log('修改')
          res = await uni.request({
            url: this.$domain.data + '/updateAddress',
            header: getApp().globalData.header,
            method: 'POST',
            data: {
              ...newAddress
            }
          })
        } else {
          res = await uni.request({
            url: this.$domain.data + '/saveAddress',
            header: getApp().globalData.header,
            method: 'POST',
            data: {
              ...newAddress
            }
          })
        }

        if (res.data.status !== 200) {
          this.$checkStatus(res.status, '保存失败')
          return
        }

        uni.showToast({ title: '保存成功' })
        this.getData()
        this.closePopup()
      })
    },

    joinRegion(region) {
      var str = ''

      const first = region[0]
      if (typeof first.value === 'undefined') {
        return region.join('/')
      }

      for (let index = 0; index < region.length; index++) {
        const element = region[index]

        str += element.value
        if (index != region.length - 1) {
          str += '/'
        }
      }

      return str
    },

    /**
     * 除去斜杠
     * @param pcd 省市区
     */
    removeXieRegion(pcd) {
      const list = pcd.split('/')
      return list.join('')
    },

    // 关闭弹窗
    closePopup() {
      this.$refs.popup.close()
      this.resetForm()
    },

    // 重置表单
    resetForm() {
      this.formData = {
        consignee: '',
        user_id: '',
        phone_number: '',
        region: [],
        province_city_district: '',
        address_detail: '',
        is_default: false
      }
    }
  }
}
</script>

<style lang="scss">
.form-region {
  width: 100upx;
  height: 100upx;
  background-color: #007aff;
}

.address-page {
  padding: 30upx;
  background: #f5f5f5;
  min-height: 100vh;

  .add-btn {
    background: $def-submit-bg;
    color: #fff;
    padding: 25upx;
    border-radius: 50upx;
    text-align: center;
    font-size: 32upx;
    margin-bottom: 30upx;
  }

  .address-list {
    height: calc(100vh - 200upx);

    .address-item {
      background: #fff;
      border-radius: 20upx;
      padding: 30upx;
      margin-bottom: 20upx;

      .header {
        display: flex;
        align-items: center;
        margin-bottom: 20upx;

        .name {
          font-size: 32upx;
          font-weight: bold;
          margin-right: 30upx;
        }

        .phone {
          font-size: 28upx;
          color: #666;
          margin-right: 30upx;
        }

        .default {
          background: #ffecec;
          color: #f56c6c;
          padding: 5upx 15upx;
          border-radius: 10upx;
          font-size: 24upx;
        }
      }

      .address {
        font-size: 28upx;
        color: #666;
        line-height: 1.6;
      }

      .action-btns {
        display: flex;
        justify-content: flex-end;
        margin-top: 30upx;
        border-top: 1upx solid #eee;
        padding-top: 30upx;

        .btn {
          padding: 10upx 30upx;
          border-radius: 40upx;
          margin-left: 20upx;
          font-size: 28upx;

          &.edit-btn {
            border: 1upx solid #007aff;
            color: #007aff;
          }

          &.delete-btn {
            border: 1upx solid #f56c6c;
            color: #f56c6c;
          }
        }
      }
    }
  }

  .address-form {
    background: #fff;
    padding: 40upx;
    border-radius: 30upx 30upx 0 0;

    .form-title {
      font-size: 36upx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 40upx;
    }

    .default-switch {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20upx 0;
      font-size: 30upx;
    }

    .form-btns {
      display: flex;
      margin-top: 50upx;

      button {
        flex: 1;
        height: 80upx;
        line-height: 80upx;
        font-size: 32upx;

        &.cancel-btn {
          background: #f8f8f8;
          color: #666;
          margin-right: 20upx;
        }

        &.confirm-btn {
          background: $def-submit-bg;
          color: #fff;
        }
      }
    }
  }
}
</style>
